/**
 * Created by zhouli on 2019/2/27
 */
import React from 'react';
import config from 'config';
import { message} from 'antd';
import {messages} from "share/common";
import FileUpload from 'components/template/ie-file-upload/file-upload';
import "styles/components/template/ie-file-upload/ie-img-upload.scss";

class IeImgUpload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      previewVisible: false,
      fileList: [],
      result: [],
      imgIsUploading: false //图片是否是正在上传的状态，用来解决 isShowDefault 为true时，上传过程中会出现显示两张图片的情况
    }
  }

  componentDidMount() {
    if (this.props.defaultFileList.length) {
      this.showDefaultFileList(this.props.defaultFileList);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.defaultFileList.length !== this.props.defaultFileList.length) {
      this.showDefaultFileList(nextProps.defaultFileList);
    }
    if (nextProps.isShowDefault) {
      if (nextProps.defaultFileList.splice && !this.state.imgIsUploading) {
        this.showDefaultFileList(nextProps.defaultFileList);
      }
    }
  }

  //为了显示默认已经上传的图片
  showDefaultFileList = (defaultFileList) => {
    let fileList = [];
    defaultFileList.map(attachment => {
      fileList.push({
        uid: attachment.attachmentOID,
        name: attachment.fileName,
        url: attachment.fileURL
      })
    });
    this.setState({fileList, result: defaultFileList})
  };
  //上传文件之前的检测，返回 false 不会上传
  beforeUpload = (file) => {
    for(let key in file){
      console.log(key)
      console.log(file[key])
    }
    if(window.ISIE9){
      //如果是 ie9 不校验
      return true;
    }
    if (this.props.fileType) {  //控制上传图片的类型
      let isFileType = false;
      this.props.fileType.map(type => {
        file.type === `image/${type}` && (isFileType = true)
      });
      if (!isFileType) {
        message.error(messages('components.key398'/*上传失败，图片格式错误*/));
        return false;
      }
    }
    if (this.props.fileSize) {  //控制上传图片的大小
      const isLtSize = file.size / 1024 / 1024 <= this.props.fileSize;
      if (!isLtSize) {
        message.error(messages('components.key656', {arg1: this.props.fileSize}/*上传失败，图片应不大于 {arg1} M*/));
        return false;
      }
    }
    this.setState({imgIsUploading: true});
    return true;
  }
  handleChange = (response) => {
    const {fileList, result} = this.state;
    fileList.push(response);
    result.push(response);
    this.setState({fileList, result, imgIsUploading: false}, () => {
      message.success(`${messages('components.key399'/*上传成功*/)}`);
      this.props.onChange(result);
    });
  };
  //预览
  handlePreview = (file) => {
    console.log(file);
    console.log(file.response ? file.response.fileURL : file.fileURL);
    window.open(file.response ? file.response.fileURL : file.url ? file.url : file.fileURL, '_blank')
  };
  render() {
    const { disabled, showMaxNum } = this.props;
    const {fileList} = this.state;
    const data = {
      attachmentType: this.props.attachmentType
    }
    return (
      <div className="ie-img-upload-wrap">
        {!disabled && (
          <FileUpload
            onChange={this.handleChange}
            token={this.props.token}
            data={data}
            beforeUpload={this.beforeUpload}
            disabled={disabled || fileList.length >= this.props.maxNum}
            uploadUrl={this.props.uploadUrl}
          />
        )}
        {showMaxNum && !disabled && (
          <div>({messages('common.max.upload.image', {max: this.props.maxNum})/*最多上传 {max} 张图片*/})</div>
        )}
        <div className="img-list-wrap">
          {fileList.length > 0 && fileList.map((img, index) => {
            return <img className="img-item" onClick={() => {
              this.handlePreview(img)
            }} key={index} src={img.fileURL || img.url}/>
          })}
          <div className="clear"/>
        </div>
      </div>
    );
  }
}

IeImgUpload.propTypes = {
  uploadUrl: React.PropTypes.string,  //上传URL
  attachmentType: React.PropTypes.any,
  defaultFileList: React.PropTypes.array,  //默认上传的文件列表
  onChange: React.PropTypes.func,  //上传成功后的回调
  maxNum: React.PropTypes.number,  //最大上传文件的数量
  token: React.PropTypes.any,
  fileType: React.PropTypes.array,  //上传文件的类型
  fileSize: React.PropTypes.number,  //上传文件的大小
  disabled: React.PropTypes.bool, //是否禁用
  showMaxNum: React.PropTypes.bool //是否显示最多上传多少图片
};
IeImgUpload.defaultProps = {
  uploadUrl: `${config.baseUrl}/api/upload/attachment/v2`,
  defaultFileList: [],
  onChange: () => {
  },
  attachmentType: "INVOICE_IMAGES",
  maxNum: 9,
  disabled: false,
  showMaxNum: false
};

export default IeImgUpload;

